import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import request from '@/utils/request';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ inventories, loading, global }) => ({
  inventories,
  global,
  loading: loading.models.inventories,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_warehouses:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      inventories: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        inventories: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'inventories/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'inventories/changeLoaded',
          });
          dispatch({
            type: 'inventories/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_warehouses`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_warehouses: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'inventories/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inventories/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'inventories/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      inventories: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="仓库">
          {getFieldDecorator('warehouse_id', {
            initialValue: searchParams.warehouse_id,
          })(
            <Select style={{ width: '120px' }} allowClear >
              {
                this.state.all_warehouses.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem>

          <FormItem label="材料名称">
            {getFieldDecorator('name', {
              initialValue: searchParams.name,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = (url) => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    request(`/${url}`, {
      method: 'POST',
      data:{
        ...formValues,
        items:[{
          material_id:this.state.editRecord.material_id,
          warehouse_area_id:this.state.editRecord.warehouse_area_id,
          count:formValues.count
        }]
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('操作成功');
        that.setState({
          [url==='outbound_lists'?'outModal':'inModal']: false,
        });
        const {
          inventories: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }

    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      name:'',
      warehouse_id: '',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `inventories/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改员工成功');
        that.setState({
          editModal: false,
        });
        const {
          inventories: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `inventories/remove`,
      payload: { id },
      callback: () => {
        message.success('删除员工成功');
        const {
          inventories: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      inventories: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            inventories: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '材料名称',
        width: 150,
        key: 'material_name',
      },
      {
        name: '所属仓库',
        width: 150,
        key: 'warehouse_name',
      },
      {
        name: '仓库区域',
        width: 150,
        key: 'warehouse_area_name',
      },
      {
        name: '库存数量',
        width: 100,
        key: 'count',
      },
      {
        name: '型号',
        width: 130,
        key: 'model',
      },
      {
        name: '单位',
        width: 70,
        key: 'unit',
      },
      {
        name: '产品供应商',
        width: 150,
        key: 'supplier_name',
      },
      {
        name: '操作',
        width: 180,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            find(this.permissions, { name: 'warehousing_operation' }) &&
            <Fragment>
              <Button
                type="primary"
                size="small"
                icon="login"
                onClick={(e) => {
                  this.setState({
                    editRecord: event.row,
                    inModal: true,
                  });
                }
                }
              >入库
              </Button>
            </Fragment>
          }
          {
            find(this.permissions, { name: 'outbound_operation' }) &&
            <Fragment>
              <Button
                type="danger"
                size="small"
                icon="logout"
                onClick={(e) => {
                  this.setState({
                    editRecord: event.row,
                    outModal: true,
                  });
                }
                }
              >出库
              </Button>
            </Fragment>
          }
        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>库存统计</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'inventories/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.inModal} modalClass="inModal" title={`"${this.state.editRecord.warehouse_area_name}" 入库 "${this.state.editRecord.material_name}"`}/>}
        className="inModal"
        destroyOnClose
        visible={this.state.inModal}
        centered
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ inModal: false });
        }}
        onOk={()=>this.handleAdd('warehousing_lists')}
      >
        <AddOrEditUser
          type={'in'}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.outModal} modalClass="outModal" title={`"${this.state.editRecord.warehouse_area_name}" 出库 "${this.state.editRecord.material_name}"`}/>}
        className="outModal"
        destroyOnClose
        visible={this.state.outModal}
        centered
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ outModal: false });
        }}
        onOk={()=>this.handleAdd('outbound_lists')}
      >
        <AddOrEditUser
          type={'out'}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
    </div>;
  }
}

export default BasicList;
